using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using TPOJ.BLL;
using TPOJ.Model;

namespace TPOJ.Web.Controllers
{
    public class SubmitController : Controller
    {
        //
        // GET: /Submit/

        public ActionResult Index(int? id,int? contests)
        {
            ViewData["problemId"] = id.ToString();
            SelectListItem item1 = new SelectListItem();
            item1.Text = "C";
            item1.Value = "C";
            item1.Selected = true;
            SelectListItem item2 = new SelectListItem();
            item2.Text = "gcc";
            item2.Value = "GCC";
            SelectListItem item3 = new SelectListItem();
            item3.Text = "C#";
            item3.Value = "C#";
            SelectListItem item4 = new SelectListItem();
            item4.Text = "java";
            item4.Value = "JAVA";
            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(item1);
            items.Add(item2);
            items.Add(item3);
            items.Add(item4);
            ViewData["language"] = items;

            var currentContests = ContestDataProxy.GetCurrentContests();
            ViewData["CurrentContests"] = currentContests;
            return View();
        }

        [Authorize]
        public ActionResult Submit(string problemId, string language, string source, string contests)
        {
            string userName = User.Identity.Name;
            AccountBO accountBO = new AccountBO();
            Account account = accountBO.GetAccountByName(userName);

            string sourcePath = Server.MapPath(@"~\Sources\");
            string testsPath = Server.MapPath(@"~\Tests\" + problemId + @"\");
            string outputPath = Server.MapPath(@"~\Outputs\");

            int? contestId=null;
            if (contests != null)
                contestId = int.Parse(contests);

            int cid = contestId ?? 0;
            var currentContests = ContestDataProxy.GetCurrentContests();
            if (!currentContests.Select(c => c.UniqueID).Contains(cid))
            {
                contestId = null;
            }
            else
            {
                foreach (var contest in currentContests)
                {
                    if (!contest.Problems.Select(p => p.UniqueID).Contains(int.Parse(problemId)))
                    {
                        contestId = null;
                    }
                }
            }

            JudgeBOAsynchronous.Judge(int.Parse(problemId), language, source, account.UniqueId, sourcePath, testsPath, outputPath, contestId, DateTime.Now);

            return RedirectToAction("Index", "Status");
        }
    }
}
